<template>
  <div class="service-details">
    <div class="page-header">
      <div class="header-title">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          {{ isDetailView ? '返回列表' : '返回仪表盘' }}
        </el-button>
        <h1>{{ isDetailView ? (singleServiceDetail?.service?.serviceName ? singleServiceDetail.service.serviceName + ' 详细信息' : '加载中...') : '服务项目进度详情' }}</h1>
        <p class="subtitle">{{ isDetailView ? '查看服务项目的详细进度和负责经理情况' : '详细查看所有服务项目的进度情况和完成状态分析' }}</p>
      </div>
    </div>

    <!-- 单个服务项目详情视图 -->
    <template v-if="isDetailView && singleServiceDetail">
      <!-- 服务项目基本信息卡片 -->
      <div class="overview-cards">
        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ singleServiceDetail.service.totalTasks }}</div>
              <div class="stat-label">分配任务数</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon progress">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ singleServiceDetail.service.completedTasks }}</div>
              <div class="stat-label">已完成任务</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon completion">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ singleServiceDetail.service.progressPercentage }}%</div>
              <div class="stat-label">完成进度</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon delayed">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ singleServiceDetail?.service?.completionCycle ? getCompletionCycleText(singleServiceDetail.service.completionCycle) : '加载中...' }}</div>
              <div class="stat-label">完成周期</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 各客户经理完成情况 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="section-header">
            <h2>
              <el-icon class="header-icon"><List /></el-icon>
              各客户经理完成情况
            </h2>
            <p class="section-desc">该服务项目在各个客户经理处的完成进度</p>
          </div>
        </template>
        
        <el-table 
          :data="singleServiceDetail.managerStats" 
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="managerName" label="客户经理" width="150">
            <template #default="scope">
              <div class="manager-info">
                <el-avatar :size="32" class="manager-avatar">
                  {{ scope.row.managerName.charAt(0) }}
                </el-avatar>
                <span class="manager-name">{{ scope.row.managerName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="totalTasks" label="总任务数" width="100" align="center" />
          <el-table-column prop="completedTasks" label="已完成" width="100" align="center" />
          <el-table-column prop="completionRate" label="完成率" width="200" align="center">
            <template #default="scope">
              <div class="completion-rate-cell">
                <el-progress 
                  :percentage="scope.row.completionRate" 
                  :status="scope.row.completionRate < 30 ? 'exception' : scope.row.completionRate < 70 ? 'warning' : 'success'"
                  :stroke-width="8"
                />
                <span class="completion-rate-text">{{ scope.row.completionRate }}%</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 最近工作日志 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="section-header">
            <h2>
              <el-icon class="header-icon"><List /></el-icon>
              最近工作日志
            </h2>
            <p class="section-desc">该服务项目的最近完成记录</p>
          </div>
        </template>
        
        <el-table 
          :data="singleServiceDetail.recentWorkLogs" 
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="clientName" label="客户名称" width="150" />
          <el-table-column prop="clientCode" label="客户代码" width="120" />
          <el-table-column prop="managerName" label="客户经理" width="120" />
          <el-table-column prop="completionDate" label="完成日期" width="120" align="center" />
          <el-table-column prop="notes" label="备注" />
          <el-table-column prop="createdAt" label="创建时间" width="120" align="center" />
        </el-table>
      </el-card>
    </template>

    <!-- 服务项目列表视图 -->
    <template v-else>
      <!-- 总体统计概览 -->
      <div class="overview-cards">
      <el-card class="overview-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Setting /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ serviceStats.totalServices }}</div>
            <div class="stat-label">总服务项目数</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon progress">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ serviceStats.inProgressServices }}</div>
            <div class="stat-label">进行中项目</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon delayed">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ serviceStats.delayedServices }}</div>
            <div class="stat-label">进度落后项目</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon completion">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ serviceStats.avgProgress }}%</div>
            <div class="stat-label">平均完成进度</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 进度落后的项目 -->
    <el-card class="section-card" shadow="never" v-if="delayedServices.length > 0">
      <template #header>
        <div class="section-header">
          <h2>
            <el-icon class="header-icon warning"><Warning /></el-icon>
            进度落后的服务项目
          </h2>
          <p class="section-desc">以下服务项目的进度需要重点关注和推进</p>
        </div>
      </template>
      
      <el-table 
        :data="delayedServices" 
        style="width: 100%"
        :default-sort="{ prop: 'progressPercentage', order: 'ascending' }"
      >
        <el-table-column prop="serviceName" label="服务项目" width="200">
          <template #default="scope">
            <div class="service-info">
              <div class="service-icon" :class="getServiceTypeClass(scope.row.serviceType)">
                <el-icon><Setting /></el-icon>
              </div>
              <div class="service-details">
                <div class="service-name">{{ scope.row.serviceName }}</div>
                <div class="service-type">{{ scope.row.serviceType }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="assignedCount" label="分配数量" width="100" align="center" />
        <el-table-column prop="completedCount" label="已完成" width="100" align="center" />
        <el-table-column prop="progressPercentage" label="完成进度" width="250" align="center" sortable>
          <template #default="scope">
            <div class="completion-rate-cell">
              <el-progress 
                :percentage="scope.row.progressPercentage" 
                :status="scope.row.progressPercentage < 30 ? 'exception' : scope.row.progressPercentage < 70 ? 'warning' : 'success'"
                :stroke-width="8"
              />
              <span class="completion-rate-text">{{ scope.row.progressPercentage }}%</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="delayDays" label="延期天数" width="100" align="center" sortable>
          <template #default="scope">
            <el-tag type="danger" size="small" v-if="scope.row.delayDays > 0">
              延期{{ scope.row.delayDays }}天
            </el-tag>
            <el-tag type="success" size="small" v-else>
              正常
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignedManagers" label="负责经理数" width="120" align="center" />
        <el-table-column prop="lastUpdateDate" label="最后更新" width="150" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="viewServiceDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 所有服务项目列表 -->
    <el-card class="section-card" shadow="never">
      <template #header>
        <div class="section-header">
          <div class="header-left">
            <h2>
              <el-icon class="header-icon"><List /></el-icon>
              所有服务项目进度
            </h2>
            <p class="section-desc">查看所有服务项目的详细进度统计</p>
          </div>
          <div class="header-right">
            <div class="filter-controls">
              <el-select
                v-model="selectedServiceType"
                placeholder="筛选服务类型"
                style="width: 150px; margin-right: 12px"
                clearable
              >
                <el-option 
                  v-for="type in serviceTypes" 
                  :key="type" 
                  :label="type" 
                  :value="type"
                />
              </el-select>
              <el-input
                v-model="searchQuery"
                placeholder="搜索项目名称"
                style="width: 200px"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
        </div>
      </template>

      <el-table 
        :data="filteredServiceList" 
        style="width: 100%"
        v-loading="loading"
        :default-sort="{ prop: 'progressPercentage', order: 'descending' }"
      >
        <el-table-column prop="serviceName" label="服务项目" width="200" fixed="left">
          <template #default="scope">
            <div class="service-info">
              <div class="service-icon" :class="getServiceTypeClass(scope.row.serviceType)">
                <el-icon><Setting /></el-icon>
              </div>
              <div class="service-details">
                <div class="service-name">{{ scope.row.serviceName }}</div>
                <div class="service-type">{{ scope.row.serviceType }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="assignedCount" label="分配数量" width="100" align="center" sortable />
        <el-table-column prop="completedCount" label="已完成" width="100" align="center" sortable />
        <el-table-column prop="progressPercentage" label="完成进度" width="250" align="center" sortable>
          <template #default="scope">
            <div class="completion-rate-cell">
              <el-progress 
                :percentage="scope.row.progressPercentage" 
                :status="scope.row.progressPercentage < 30 ? 'exception' : scope.row.progressPercentage < 70 ? 'warning' : 'success'"
                :stroke-width="8"
              />
              <span class="completion-rate-text">{{ scope.row.progressPercentage }}%</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="assignedManagers" label="负责经理数" width="120" align="center" sortable />
        <el-table-column prop="avgCompletionDays" label="平均用时(天)" width="120" align="center" sortable />
        <el-table-column prop="lastUpdateDate" label="最后更新" width="150" align="center" sortable />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)" 
              size="small"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewServiceDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  ArrowLeft,
  Setting,
  Clock,
  Warning,
  CircleCheck,
  List,
  Search,
  Trophy
} from '@element-plus/icons-vue';
import { trpc } from '../../utils/trpc';

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const searchQuery = ref('');
const selectedServiceType = ref('');

// 判断是否为单个服务项目详情页面
const isDetailView = computed(() => !!route.params.id);
const serviceId = computed(() => isDetailView.value ? Number(route.params.id) : null);

// 服务项目总体统计
const serviceStats = ref({
  totalServices: 0,
  inProgressServices: 0,
  delayedServices: 0,
  avgProgress: 0,
});

// 进度落后的服务项目
const delayedServices = ref([]);

// 所有服务项目列表
const serviceList = ref([]);

// 服务类型列表
const serviceTypes = ref([]);

// 单个服务项目详情数据
const singleServiceDetail = ref(null);

// 过滤后的服务项目列表
const filteredServiceList = computed(() => {
  let filtered = serviceList.value;
  
  if (searchQuery.value) {
    filtered = filtered.filter(service => 
      service.serviceName.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
  }
  
  if (selectedServiceType.value) {
    filtered = filtered.filter(service => 
      service.serviceType === selectedServiceType.value
    );
  }
  
  return filtered;
});

// 获取服务类型样式类
const getServiceTypeClass = (serviceType: string) => {
  const typeMap = {
    '客户拜访': 'visit',
    '满意度调研': 'survey',
    '团队协作': 'team',
    '诚信建设': 'integrity',
    '客户评价': 'evaluation',
    '通用服务': 'generic'
  };
  return typeMap[serviceType] || 'generic';
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap = {
    '正常': 'success',
    '延期': 'danger',
    '暂停': 'warning',
    '进行中': 'primary'
  };
  return statusMap[status] || 'info';
};

// 转换完成周期为中文显示
const getCompletionCycleText = (cycle: string) => {
  const cycleMap = {
    'daily': '每日',
    'weekly': '每周', 
    'monthly': '每月',
    'quarterly': '每季度',
    'yearly': '每年'
  };
  return cycleMap[cycle] || cycle;
};

// 返回按钮逻辑
const goBack = () => {
  if (isDetailView.value) {
    router.push('/service-details');
  } else {
    router.push('/dashboard');
  }
};

// 查看服务详情
const viewServiceDetail = (service) => {
  router.push(`/service-details/${service.id}`);
};

// 加载服务项目数据
const loadServiceData = async () => {
  loading.value = true;
  try {
    if (isDetailView.value && serviceId.value) {
      // 加载单个服务项目详情
      console.log('开始加载单个服务项目详情，ID:', serviceId.value);
      const result = await trpc.stats.serviceDetail.query({ serviceId: serviceId.value });

      console.log('单个服务详情API返回结果:', result);

      if (result.success && result.data) {
        singleServiceDetail.value = result.data;
        console.log('单个服务项目详情加载成功:', result.data);
        ElMessage.success('服务项目详情加载成功');
      } else {
        console.error('获取服务项目详情失败:', result.message);
        ElMessage.error(result.message || '获取服务项目详情失败');
      }
    } else {
      // 加载服务项目列表数据
      console.log('开始加载服务项目数据...');
      const result = await trpc.stats.serviceDetails.query({});

      console.log('API返回结果:', result);

      if (result.success && result.data) {
        serviceStats.value = result.data.stats;
        delayedServices.value = result.data.delayedServices;
        serviceList.value = result.data.allServices;
        serviceTypes.value = result.data.serviceTypes || [];
        
        console.log('服务项目数据加载成功:', result.data);
        ElMessage.success('服务项目数据加载成功');
      } else {
        console.error('获取服务项目数据失败:', result.message);
        ElMessage.error(result.message || '获取服务项目数据失败');
      }
    }
  } catch (error) {
    console.error('加载服务项目数据失败:', error);
    ElMessage.error('加载数据失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadServiceData();
});
</script>

<style scoped>
.service-details {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

.page-header {
  margin-bottom: 32px;
}

.header-title h1 {
  margin: 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #262626;
}

.back-btn {
  font-size: 14px;
  padding: 0;
  margin-bottom: 8px;
  color: #1890ff;
}

.back-btn:hover {
  color: #40a9ff;
}

.subtitle {
  margin: 0;
  color: #8c8c8c;
  font-size: 16px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.overview-card {
  border-radius: 12px;
  transition: transform 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.progress {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.delayed {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-icon.completion {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #262626;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

.section-card {
  margin-bottom: 32px;
  border-radius: 12px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left h2, .section-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
}

.header-icon.warning {
  color: #faad14;
}

.section-desc {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.filter-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.service-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.service-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.service-icon.visit {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.service-icon.survey {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.service-icon.team {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.service-icon.integrity {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.service-icon.evaluation {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.service-icon.generic {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.service-details {
  flex: 1;
}

.service-name {
  font-weight: 500;
  color: #262626;
  font-size: 14px;
  margin-bottom: 2px;
}

.service-type {
  font-size: 12px;
  color: #8c8c8c;
}

.manager-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.manager-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.manager-name {
  font-weight: 500;
}

.completion-rate-cell {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.completion-rate-cell .el-progress {
  flex: 1;
  min-width: 120px;
}

.completion-rate-text {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
  min-width: 40px;
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .service-details {
    padding: 16px;
  }
  
  .overview-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-controls {
    flex-direction: column;
    width: 100%;
  }
  
  .stat-number {
    font-size: 24px;
  }
}
</style>